package com.ruizhong.centercontroll.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SaltedMD5Encryptor {

    // Method to convert a password to MD5 hash with username as salt
    public static String getSaltedMD5Hash(String username, String password) {
        try {
            // Create MD5 MessageDigest instance
            MessageDigest md = MessageDigest.getInstance("MD5");

            // Combine username and password to create the salted input
            String saltedInput = username + password + "3";

            // Convert salted input to byte array and update the digest
            md.update(saltedInput.getBytes());

            // Compute the message digest (hash) and convert it to hex string
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();

            // Convert byte array to hex string
            for (byte b : digest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            // Return the hex string
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // Example usage
        String username = "user123";
        String password = "myPassword123";
        String saltedMD5Hash = getSaltedMD5Hash(username, password);
        System.out.println("Salted MD5 Hash: " + saltedMD5Hash);
    }
}